package guestbook;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;

import data.Book;

@SuppressWarnings("serial")
public class DeleteBookServlet extends HttpServlet {
	private static final Logger s_log = Logger.getLogger(DeleteBookServlet.class.getName());
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {			
		
		String strBookStore = req.getParameter("bookStore");
		Key keyBookStore = KeyFactory.createKey("BookStore", strBookStore);
		
		String strIsbn = req.getParameter("content");
		s_log.info("Request to delete ISBN:" + strIsbn);
		if (strIsbn == null || strIsbn.trim().isEmpty())
		{
			s_log.warning("empty content for deletion");
			resp.sendRedirect("/bookstore.jsp?bookStore=" + strBookStore);
			return;
		}
		
		int nIsbn = -1;
		try
		{
			nIsbn = Integer.valueOf(strIsbn);
		}
		catch (NumberFormatException e)
		{
			s_log.warning("Invalid ISBN for deletion:" + nIsbn);
			resp.sendRedirect("/bookstore.jsp?bookStore=" + strBookStore);
			return;
		}
		
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Filter filter = new FilterPredicate(Book.ISBN, FilterOperator.EQUAL, nIsbn);
		Query query = new Query("Book", keyBookStore).setFilter(filter);
		List<Entity> lsEntBook = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));
		for (Entity entBook : lsEntBook)
		{
			s_log.info("Delete book:" + entBook.getProperty(Book.NAME));
			datastore.delete(entBook.getKey());
		}
		
		resp.sendRedirect("/bookstore.jsp?bookStore=" + strBookStore);				
	}

}
